package com.zjdiepu.www.manage.api.cw;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.AddedStatus1;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.LoanEditStatus;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.SortFieldType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.DateUtil;
import com.zjdiepu.www.common.util.NumberUtil;
import com.zjdiepu.www.commpent.RedisObjectClient;
import com.zjdiepu.www.commpent.ViewScopeControllerHelper;
import com.zjdiepu.www.commpent.mapper.cw.CwRemitCarVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.AbstractYwBusinessLoanVoNewMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessBuyerVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessCarVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessDetailMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwFeesVoMapper;
import com.zjdiepu.www.ibiz.base.IDpBaseDataDictionaryService;
import com.zjdiepu.www.ibiz.cache.ICachedDictionaryService;
import com.zjdiepu.www.ibiz.cw.ICwIncomeExpensesItemService;
import com.zjdiepu.www.ibiz.cw.ICwRemitCarService;
import com.zjdiepu.www.ibiz.other.IOtherAuditInfoService;
import com.zjdiepu.www.ibiz.system.IBaseBusiUnitService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessBuyerService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessCarService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessExtrasService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessLoanEditService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessLoanService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.ibiz.yw.IYwFeesService;
import com.zjdiepu.www.ibiz.yw.IYwFeesSubService;
import com.zjdiepu.www.ibiz.yw.IYwFundApplyService;
import com.zjdiepu.www.model.base.dto.SimpleDataDictionary;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.cw.dto.CwRemitCar;
import com.zjdiepu.www.model.cw.ext.CwRemitCarExt;
import com.zjdiepu.www.model.cw.response.CwFundItem;
import com.zjdiepu.www.model.other.dto.OtherAuditInfo;
import com.zjdiepu.www.model.system.dto.BaseBusiUnit;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessBuyer;
import com.zjdiepu.www.model.yw.dto.YwBusinessCar;
import com.zjdiepu.www.model.yw.dto.YwBusinessLoan;
import com.zjdiepu.www.model.yw.dto.YwBusinessLoanEdit;
import com.zjdiepu.www.model.yw.dto.YwFees;
import com.zjdiepu.www.model.yw.dto.YwFundApply;
import com.zjdiepu.www.model.yw.request.YwBusinessQueryRequest;
import com.zjdiepu.www.model.yw.response.YwBusinessDetail;
import com.zjdiepu.www.util.ExceptionHelper;
import com.zjdiepu.www.util.YwExtHelper;

/**
 * 垫提车款Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月11日 20时36分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "CwRemitCarController", produces="application/json;charset=UTF-8")
@Api(tags = {"垫提车款"}, produces="application/json;charset=UTF-8")
public class CwRemitCarController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(CwRemitCarController.class);
	
    @Resource
    private ICwRemitCarService cwRemitCarService;
    @Resource
    private IYwBusinessService ywBusinessService;
    @Resource
    private IYwFeesService ywFeesService;
    @Resource
    private IYwBusinessCarService ywBusinessCarService;
    @Resource
    private IYwBusinessLoanService ywBusinessLoanService;
    @Resource
    private IYwBusinessLoanEditService ywBusinessLoanEditService;
    @Resource
    private IYwFundApplyService ywFundApplyService;
    @Resource
    private IYwFeesSubService ywFeesSubService;
    @Resource
    private IYwBusinessExtrasService ywBusinessExtrasService;
    @Resource
    private ICwIncomeExpensesItemService cwIncomeExpensesItemService;
    @Resource
    private IYwBusinessBuyerService ywBusinessBuyerService;
    @Resource
    private IBaseBusiUnitService baseBusiUnitService;
    @Resource
    private IDpBaseDataDictionaryService dpBaseDataDictionaryService;
    @Resource
    private YwBusinessVoMapper ywBusinessVoMapper;
    @Resource
    private ICachedDictionaryService cachedDictionaryService;
    @Resource
    private YwFeesVoMapper ywFeesVoMapper;
    @Resource
    private YwBusinessCarVoMapper ywBusinessCarVoMapper;
    @Resource
    private AbstractYwBusinessLoanVoNewMapper ywBusinessLoanVoMapper;
    @Resource
    private YwBusinessBuyerVoMapper ywBusinessBuyerVoMapper;
    @Resource
    private CwRemitCarVoMapper cwRemitCarVoMapper;
    @Resource
    private YwBusinessDetailMapper ywBusinessDetailMapper;
    @Resource
    private IOtherAuditInfoService otherAuditInfoService;
    @Resource
    private RedisObjectClient redisObjectClient;
    
    /**
     * 打印的收支项目
     */
    private static final List<String> KEYS = Arrays.asList(new String[]{"01", "35", "03", "25", "22", "02", "33", "06", "07", "08", "32", "05", "26"});
    
    /**
     * 判断是否已退贷
     * @author xiongxiaotun <br/>
     * @Title busiStatus  <br/>
     * @Description 判断是否已退贷<br/>
     * @param busiId
     * @param request
     * @return
     * @version V1.0  <br/>
     */
     @ApiOperation(value = "判断是否已退贷", response = Boolean.class, httpMethod="POST")
     @RequestMapping(value = "busiStatus", method = {RequestMethod.GET, RequestMethod.POST})
     public ApiResponse busiStatus(String busiId) {
     	if(StringUtils.isBlank(busiId)) {
     		ExceptionHelper.thow(ResultFlagType.MISSING.getCode().toString(), "业务ID不能为空");
     	}
    	YwBusiness ywBusiness = ywBusinessService.selectById(busiId);
    	if(null == ywBusiness) {
    		ExceptionHelper.thow(ResultFlagType.MISSING.getCode().toString(),"业务记录不存在");
    	}
    	Integer busiStatus = ywBusiness.getBusiStatus();
    	if(null == busiStatus) {
    		busiStatus = 0; //列表页已经过滤，不会出现
    	}
    	return ApiResponse.success(busiStatus <= 500);
     }
    
   /**
    * 打印垫款信息
    * @author xiongxiaotun <br/>
    * @Title print  <br/>
    * @Description 打印垫款信息  <br/>
    * @param busiId
    * @param request
    * @return
    * @version V1.0  <br/>
    */
    @ApiOperation(value = "打印垫款信息", response = Boolean.class, httpMethod="POST", tags={"打印垫款信息"})
    @RequestMapping(value = "print", method = {RequestMethod.GET, RequestMethod.POST})
    public ApiResponse print(String busiId, @RequestParam(defaultValue="0")boolean check, @RequestParam(defaultValue="0")boolean modifyAudit, String loanEditId, HttpServletResponse response) {
    	AbstractSysUser currentUser = getCurrentUser();
    	//展示数据
    	Map<String, Object> responseData = CollectionInitUtil.emptyMap();
    	responseData.put("userName", currentUser.getName());
    	responseData.put("now", DateUtil.dateTo8String(new Date()));
    	
    	//业务详情
		YwBusinessDetail ywBusinessDetail = ywBusinessService.getMultiById(busiId);
		if (null == ywBusinessDetail) {
			ExceptionHelper.thow("999", "业务不存在或已被删除");
		}
		ywBusinessDetailMapper.mapper(ywBusinessDetail);
		String orgCode = ywBusinessDetail.getOrgCode();
		if(StringUtils.isNotBlank(orgCode)) {
			if(orgCode.length() > 4) {
				orgCode = orgCode.substring(0,4);
				BaseBusiUnit baseBusiUnit_ = new BaseBusiUnit();
				baseBusiUnit_.setOrgCode(orgCode);
				baseBusiUnit_.notDeleted();
				BaseBusiUnit baseBusiUnit = baseBusiUnitService.selectRefined(baseBusiUnit_);
				ywBusinessDetail.setProviceOrgName(baseBusiUnit.getOrgName());
			} else {
				ywBusinessDetail.setProviceOrgName(ywBusinessDetail.getOrgName());
			}
		}
		responseData.put("ywBusinessDetail", ywBusinessDetail);
		
		//主借人
		YwBusinessBuyer ywBusinessBuyer_ = new YwBusinessBuyer();
		ywBusinessBuyer_.setBusiId(busiId);
		ywBusinessBuyer_.setCarManType("03");
		ywBusinessBuyer_.setDpStatus(DpStatus.NORMAL.getCode());
		YwBusinessBuyer ywBusinessBuyer = ywBusinessBuyerService.selectRefined(ywBusinessBuyer_);
		if (null == ywBusinessBuyer) {
			ExceptionHelper.thow("999", "主借人记录不存在或已被删除");
		}
		ywBusinessBuyerVoMapper.mapper(ywBusinessBuyer);
		responseData.put("ywBusinessBuyer", ywBusinessBuyer);
		
		//申请贷款修改审核B
		YwBusinessLoanEdit ywBusinessLoanEdit = new YwBusinessLoanEdit();
		if(modifyAudit) {
			if(StringUtils.isBlank(loanEditId)) {
				ywBusinessLoanEdit.setDpStatus(DpStatus.NORMAL.getCode());
				ywBusinessLoanEdit.setLoanEditStatus(LoanEditStatus.SHEN_HE_2_SHEN_HE_ZHONG.getCode());
				ywBusinessLoanEdit.setBusiId(busiId);
				ywBusinessLoanEdit = ywBusinessLoanEditService.selectRefined(ywBusinessLoanEdit);
			} else {
				ywBusinessLoanEdit = ywBusinessLoanEditService.selectById(loanEditId);
			}
			if(ywBusinessLoanEdit == null) {
				ExceptionHelper.thow("999","贷款修改申请记录不存在或已被删除");
			}
			responseData.put("shenqin", ywBusinessLoanEdit.getCreatorName());
			responseData.put("shenqinDate", DateUtil.dateTo8String(new Date(ywBusinessLoanEdit.getCreated() * 1000L)));
		}
		
		//按揭日报表
		YwFees ywFees;
		if(modifyAudit) {
			ywFees = new YwFees();
			BeanUtils.copyProperties(ywBusinessLoanEdit, ywFees);
			
			YwFees ywFees_ = new YwFees();
			ywFees_.setDpStatus(DpStatus.NORMAL.getCode());
			ywFees_.setBusiId(busiId);
			ywFees_ = ywFeesService.selectRefined(ywFees_);
			if(null == ywFees_) {
				ExceptionHelper.thow("999", "未登记按揭日报表");
			}
			ywFees.setTypeBalance(ywFees_.getTypeBalance());
		} else {
			YwFees ywFees_ = new YwFees();
			ywFees_.setDpStatus(DpStatus.NORMAL.getCode());
			ywFees_.setBusiId(busiId);
			ywFees = ywFeesService.selectRefined(ywFees_);
			if(null == ywFees) {
				ExceptionHelper.thow("999", "未登记按揭日报表");
			}
		}
		
		ywFeesVoMapper.mapper(ywFees);
		ywFees.setRebateAreaString(NumberUtil.format(ywFees.getRebateArea() == null ? 0 : ywFees.getRebateArea(), 2));
		ywFees.setRebateDealerString(NumberUtil.format(ywFees.getRebateDealer() == null ? 0 : ywFees.getRebateDealer(), 2));
		ywFees.setRebateProvinceString(NumberUtil.format(ywFees.getRebateProvince() == null ? 0 : ywFees.getRebateProvince(), 2));
		responseData.put("ywFees", ywFees);
		
		//申请垫资
		YwFundApply ywFundApply_ = new YwFundApply();
		ywFundApply_.setDpStatus(DpStatus.NORMAL.getCode());
		ywFundApply_.setBusiId(busiId);
		YwFundApply ywFundApply = ywFundApplyService.selectRefined(ywFundApply_);
		if(null == ywFundApply) {
			ExceptionHelper.thow("999", "申请垫资不存在或已被删除");
		}
		ywFundApply.setDateFistString(DateUtil.dateTo8String3(ywFundApply.getDateFist()));
		responseData.put("ywFundApply", ywFundApply);
		
		//垫提车款
		CwRemitCar cwRemitCar_ = new CwRemitCar();
		cwRemitCar_.setDpStatus(DpStatus.NORMAL.getCode());
		cwRemitCar_.setBusiId(busiId);
//		cwRemitCar_.setStatusRemit(RemitStatus.YI_TI_JIAO.getCode());
		cwRemitCar_.setOrderSql("`MODIFIED` DESC"); //最近的一条记录
		CwRemitCar cwRemitCar = cwRemitCarService.selectRefined(cwRemitCar_);
		if(null != cwRemitCar) {
			/*ExceptionHelper.thow("999", "垫提车款记录不存在、已被删除或已退提车款");
		} else {*/
			cwRemitCarVoMapper.mapper(cwRemitCar);
			cwRemitCar.setTimeArriveString(DateUtil.dateTo8String3(cwRemitCar.getTimeArrive()));
			cwRemitCar.setTimeAuditString(DateUtil.dateTo8String3(cwRemitCar.getTimeAudit()));
			cwRemitCar.setTimeRemitString(DateUtil.dateTo8String3(cwRemitCar.getTimeRemit()));
		}
		responseData.put("cwRemitCar", cwRemitCar);
		// 查询车辆
    	YwBusinessCar ywBusinessCar_ = new YwBusinessCar();
		ywBusinessCar_.setDpStatus(DpStatus.NORMAL.getCode());
		ywBusinessCar_.setBusiId(busiId);
    	YwBusinessCar ywBusinessCar = ywBusinessCarService.selectRefined(ywBusinessCar_);
    	if(null == ywBusinessCar) {
    		ExceptionHelper.thow("999", "车辆记录不存在或已被删除");
    	}
    	if(modifyAudit) {
    		ywBusinessCar.setPrice(ywBusinessLoanEdit.getCarPrice());
    	}
		ywBusinessCarVoMapper.mapper(ywBusinessCar);
		
		// 车贷信息 
		YwBusinessLoan ywBusinessLoan;
		if(modifyAudit) {
			ywBusinessLoan = new YwBusinessLoan();
			BeanUtils.copyProperties(ywBusinessLoanEdit, ywBusinessLoan);
		} else {
			String carId = ywBusinessCar.getId();
			YwBusinessLoan ywBusinessLoan_ = new YwBusinessLoan();
			ywBusinessLoan_.setDpStatus(DpStatus.NORMAL.getCode());
			ywBusinessLoan_.setBusiId(busiId);
			ywBusinessLoan_.setCarId(carId);
			ywBusinessLoan = ywBusinessLoanService.selectRefined(ywBusinessLoan_);
			if(null == ywBusinessLoan) {
				ExceptionHelper.thow("999", "车贷记录不存在或已被删除");
			}
		}
		ywBusinessLoanVoMapper.mapper(ywBusinessLoan);
		
		ywBusinessLoan.setCompanyRateString(NumberUtil.format(ywBusinessLoan.getCompanyRate(), 4));
		ywBusinessLoan.setLoanAmountString(NumberUtil.format(ywBusinessLoan.getLoanAmount(), 2));
		ywBusinessLoan.setSignLoanAmountString(NumberUtil.format(ywBusinessLoan.getSignLoanAmount(), 2));
		ywBusinessLoan.setServicePriceString(NumberUtil.format(ywBusinessLoan.getServicePrice(), 2));
		responseData.put("ywBusinessLoan", ywBusinessLoan);
		
		ywBusinessCar.setPriceString(NumberUtil.format((ywBusinessCar.getPrice() == null ? 0 : ywBusinessCar.getPrice()), 2));
		
		responseData.put("ywBusinessCar", ywBusinessCar);
		
		if(check) { //仅仅检查是否有异常
			return ApiResponse.success(true);
		}
    	//按揭日报表
    	List<Map<String, Double>> fees = ywFeesSubService.countReceiveByBusiId(busiId, null);
    	//实收
    	List<Map<String, Double>> remits = cwIncomeExpensesItemService.countReceiveByBusiId(busiId, null);
    	
    	Map<String, CwFundItem> fundItem = CollectionInitUtil.emptyMap();
		redisObjectClient.execute(new RedisCallback<Boolean>() {
			@Override
			public Boolean doInRedis(RedisConnection redisConnection)
					throws DataAccessException {
				for(String key : KEYS) {
					CwFundItem cwFundItem = new CwFundItem();
					cwFundItem.setKey(key);
					SimpleDataDictionary fundItems = redisObjectClient.hGet(redisConnection, SimpleDataDictionary.class.getSimpleName(), key, DataDicType.FUND_ITEM.getCode());
					if(null == fundItems) {
						logger.debug("收支项目key：" + key + "不存在");
						continue;
					}
					if(!KEYS.contains(key)) {
						continue;
					}
					cwFundItem.setName(fundItems.getName());
					cwFundItem.setFeeCount(ViewScopeControllerHelper.getItem(fees, key));
					cwFundItem.setFeeCountString(NumberUtil.format(cwFundItem.getFeeCount(), 2));
					cwFundItem.setRemitCount(ViewScopeControllerHelper.getItem(remits, key));
					cwFundItem.setRemitCountString(NumberUtil.format(cwFundItem.getRemitCount(), 2));
					fundItem.put("key" + key, cwFundItem);
				}
				return true;
			}
		});
    	responseData.put("fundItem", fundItem);
    	
    	//总计
    	CwFundItem totalItem = new CwFundItem();
    	totalItem.setFeeCount(countItems(fees, CollectionInitUtil.emptyList()));
    	totalItem.setFeeCountString(NumberUtil.format(totalItem.getFeeCount(), 2));
    	totalItem.setRemitCount(countItems(remits, CollectionInitUtil.emptyList()));
    	totalItem.setRemitCountString(NumberUtil.format(totalItem.getRemitCount(), 2));
    	responseData.put("totalItem", totalItem);
    	
        String templetPath;
        if(modifyAudit) {
        	OtherAuditInfo otherAuditInfoParam = new OtherAuditInfo();
        	otherAuditInfoParam.setBusiId(busiId);
        	otherAuditInfoParam.setModeId(ModeIDType.XGDKSHY.getCode());
        	OtherAuditInfo otherAuditInfo1 = otherAuditInfoService.selectRefined(otherAuditInfoParam);
        	if(null != otherAuditInfo1) {
        		responseData.put("shenheRen1", otherAuditInfo1.getCreatorName());
        		responseData.put("shenheDate1", DateUtil.dateTo8String(new Date(otherAuditInfo1.getCreated() * 1000L)));
        	}
        	
        	otherAuditInfoParam.setModeId(ModeIDType.XGDKSHE.getCode());
        	OtherAuditInfo otherAuditInfo2 = otherAuditInfoService.selectRefined(otherAuditInfoParam);
        	if(null != otherAuditInfo2) {
        		responseData.put("shenheRen2", otherAuditInfo2.getCreatorName());
        		responseData.put("shenheDate2", DateUtil.dateTo8String(new Date(otherAuditInfo2.getCreated() * 1000L)));
        	}
        	
        	templetPath = "/WEB-INF/templet/cai_wu_shen_qing_xiu_gai_que_ren_biao_@_cai_wu.xls";
        } else {
        	templetPath = "/WEB-INF/templet/cai_wu_dian_kuan_que_ren_biao_@_cai_wu.xls";
        }
    	String templet = request.getSession(true).getServletContext().getRealPath(templetPath);
		try (FileInputStream is = new FileInputStream(templet); ){
			XLSTransformer transformer = new XLSTransformer();  
			Workbook workbook = transformer.transformXLS(is, responseData);
			String fileName = "财务垫款确认表-" + ywBusinessDetail.getCustomerName();
			response.reset();
			response.addHeader("Content-Disposition",
					"attachment;filename=" + new String(fileName.getBytes(isIE(request)?"GBK":"UTF-8"), "ISO-8859-1") +".xls");
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			OutputStream outPutStream = response.getOutputStream();
			workbook.write(outPutStream); 
		} catch (ParsePropertyException | InvalidFormatException | IOException e) {
			logger.error("导出财务垫款确认表异常.busiId is {}.异常栈:{}",busiId, e);
		}
		return null;
    }
    
    /**
	 * 收支明细总计
	 * @param items
	 * @param key
	 * @return
	 */
    public static double countItems(List<Map<String, Double>> items, List<String> exludeKeys){
    	if(CollectionUtils.isEmpty(items)) {
    		return 0;
    	}
    	double sum = 0;
    	for(Map<String, Double> item : items) {
    		Object dataKey = item.get("KEY");
    		if(dataKey == null) {
    			continue;
    		}
    		String realKey = "";
    		if(dataKey instanceof String) {
    			realKey = (String)dataKey;
    		} else {
    			realKey = new BigDecimal(dataKey.toString()).setScale(0).toString();
    		}
    		if(!KEYS.contains(realKey)) {
    			continue;
    		}
    		if(!exludeKeys.contains(realKey)) {
    			sum += item.get("VALUE") == null ? 0 : item.get("VALUE");
    		}
    	}
    	return sum;
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: checkLoanEditLock  <br/>
     * @Description: 检查是否锁单 <br/>
     * @param busiId
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "检查是否锁单", response = Boolean.class, httpMethod="POST")
    @RequestMapping(value = "checkLoanEditLock", method = RequestMethod.POST)
    public ApiResponse checkLoanEditLock(String busiId) {
    	getCurrentUser();
    	if(StringUtils.isBlank(busiId)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
        return ApiResponse.success(ywBusinessExtrasService.checkLoanEditLock(busiId));
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: remitCar  <br/>
     * @Description: 保存贷后信息 <br/>
     * @param cwRemitCar
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "垫提车款登记", response = Boolean.class, httpMethod="POST", tags={"垫提车款"})
    @RequestMapping(value = "remitCar", method = RequestMethod.POST)
    public ApiResponse remitCar(@ModelAttribute CwRemitCar cwRemitCar, @RequestParam(defaultValue="0") boolean commit) {
    	AbstractSysUser currentUser = getCurrentUser();
    	String busiId = cwRemitCar.getBusiId();
    	if(StringUtils.isBlank(busiId)) {
     		ExceptionHelper.thow(ResultFlagType.MISSING.getCode().toString(), "业务ID不能为空");
     	}
    	YwBusiness ywBusiness = ywBusinessService.selectById(busiId);
    	if(null == ywBusiness) {
    		ExceptionHelper.thow(ResultFlagType.MISSING.getCode().toString(),"业务记录不存在");
    	}
    	Integer busiStatus = ywBusiness.getBusiStatus();
    	if(null == busiStatus) {
    		busiStatus = 0;
    	}
    	if(busiStatus > BusiStatus.YIN_HANG_YI_FANG_KUAN.getCode()) {
    		ExceptionHelper.thow("999", "该订单已退贷，不能垫款");
    	}
        return cwRemitCarService.saveRemitCar(cwRemitCar, commit, currentUser);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: remitCarList <br/>
     * @Description: 垫提车款列表 <br/>
     * @param ywBusinessQueryRequest
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "垫提车款列表",response = YwBusiness.class, httpMethod="POST", tags={"垫提车款"})
    @RequestMapping(value = "remitCarList", method = RequestMethod.POST)
    public ApiResponse remitCarList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest){
    	SysUser sysUser = (SysUser)getCurrentUser();
        PageVo page = getPage(ywBusinessQueryRequest);
        ywBusinessQueryRequest.setBaseWhere();
        ywBusinessQueryRequest.setBankLoan(sysUser.getLoanBank());
        ywBusinessQueryRequest.setCodeUnits(sysUser.getCodeUnits());
        ywBusinessQueryRequest.setNeedLimit(true);
        YwExtHelper.initExt(ywBusinessQueryRequest, SortFieldType.TIME_AUDIT_FINISH);
        ywBusinessQueryRequest.setAddedStatus1(AddedStatus1.DA_KUAN_ZHONG.getCode());
        
//      业务状态在风控审核完成（包括）和银行已放款之间（包括）
        ywBusinessQueryRequest.setMinBusiStatus(BusiStatus.SHEN_PI_WAN_CHENG.getCode());
        ywBusinessQueryRequest.setMaxBusiStatus(BusiStatus.YIN_HANG_YI_FANG_KUAN.getCode());
//      ywBusinessQueryRequest.addBusiStatus(BusiStatus.DA_KUAN_ZHONG.getCode());
//      ywBusinessQueryRequest.addBusiStatus(BusiStatus.YI_TUI_KUAN.getCode());
        
        //垫提车款列表调整：去掉 欠资料状态为“资料齐全”或者“资料已补齐” 的限制    zhangpp
        //ywBusinessQueryRequest.addLessInformationStatus(LessInformationStatus.ZI_LIAO_QI_QUAN.getCode());
        //ywBusinessQueryRequest.addLessInformationStatus(LessInformationStatus.ZI_LIAO_YI_BU_QI.getCode());
        
//      ywBusinessQueryRequest.setCodeUnits(currentUser.getCodeUnits());
//        ywBusinessQueryRequest.setOrderSql("B.`TIME_AUDIT_FINISH`");
        
        Date createOrderTimeStartDate = ywBusinessQueryRequest.getCreateOrderTimeStartDate();
        if(createOrderTimeStartDate != null) {
        	ywBusinessQueryRequest.setCreateOrderTimeStart(DateUtil.truncAndAddDays(createOrderTimeStartDate, 0).getTime() / 1000);
        } 
        Date createOrderTimeEndDate = ywBusinessQueryRequest.getCreateOrderTimeEndDate();
        if(createOrderTimeEndDate != null){
        	ywBusinessQueryRequest.setCreateOrderTimeEnd(DateUtil.truncAndAddDays(createOrderTimeEndDate, 1).getTime() / 1000);
        }
        int records = ywBusinessService.countMultiByExt(ywBusinessQueryRequest);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusiness> ywBusinesss = ywBusinessService.selectMultiByExt(ywBusinessQueryRequest);
            ywBusinessVoMapper.mapper(ywBusinesss);
            page.setRows(ywBusinesss);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增垫提车款 <br/>
     * @param cwRemitCar
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增垫提车款", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute CwRemitCar cwRemitCar) {
    	AbstractSysUser currentUser = getCurrentUser();
    	cwRemitCar.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	cwRemitCar.setModifierName(currentUser.getName());
        cwRemitCarService.saveUpdateAndDelete(cwRemitCar, OperateType.add);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除垫提车款<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除垫提车款", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	cwRemitCarService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: disable  <br/>
     * @Description: 禁用垫提车款<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用垫提车款", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	cwRemitCarService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: enable <br/>
     * @Description: 启用垫提车款<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用垫提车款", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	cwRemitCarService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改垫提车款 <br/>
     * @param cwRemitCar
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改垫提车款", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute CwRemitCar cwRemitCar) {
    	AbstractSysUser currentUser = getCurrentUser();
    	cwRemitCar.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	cwRemitCar.setModifierName(currentUser.getName());
    	cwRemitCarService.saveUpdateAndDelete(cwRemitCar, OperateType.edit);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询垫提车款<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询垫提车款", response = CwRemitCar.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       CwRemitCar cwRemitCar = cwRemitCarService.selectById(id);
       if(null == cwRemitCar) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(cwRemitCar);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询垫提车款 <br/>
     * @param cwRemitCarExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询垫提车款",response = CwRemitCar.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute CwRemitCarExt cwRemitCarExt){
        cwRemitCarExt.notDeleted();
        PageVo page = getPage(cwRemitCarExt);
        int records = cwRemitCarService.countByExt(cwRemitCarExt);
        page.setRecords(records);
        if (records > 0) {
            List<CwRemitCar> cwRemitCars = cwRemitCarService.selectByExt(cwRemitCarExt);
            page.setRows(cwRemitCars);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    @ApiOperation(value = "更新到账时间",response = Boolean.class, httpMethod="POST", tags={"更新"})
    @RequestMapping(value = "updateArriveTime", method = RequestMethod.POST)
    public ApiResponse updateArriveTime(Date timeArrive,String id){
    	List<String> ids = Arrays.asList(id.split(","));
    	cwRemitCarService.updateArriveTime(timeArrive,ids);
    	return ApiResponse.success(true);
    }
}
